package com.gensdai.leliang.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.classic.common.MultipleStatusView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.adapter.AddressAdapterRec;
import com.gensdai.leliang.common.bean.AddressBean;
import com.gensdai.leliang.entity.Address;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 收货地址的列表
 * Created by Administrator on 2017/6/2.
 */

public class AddressListActivity extends BaseActivity {


    @BindView(R.id.rec_addresslist)
    RecyclerView recAddresslist;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.main_multiplestatusview)
    MultipleStatusView mainMultiplestatusview;

    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    List<Address> mData;

    private String userid = "";
    AddressAdapterRec menuAdapter;

    @Override
    protected String getTitleStr() {
        return "收获地址";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_address;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.address_list_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.action_add_address:
                startActivity(new Intent(this, New_delivery_address.class));
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        userid = PreferencesUtils.getStringPreference(this, OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //获取用户id没有登陆就是没有
        initRecycler();


        if (TextUtils.isEmpty(userid)) {
            //用户ID为空值  不允许做操作 只允许他去登陆
        } else {
            getAddressRequest();
        }
    }

    private void getAddressRequest() {

        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);   //用户id
        getdata(params);
    }

    //返回字符串类型
    private void getdata(Map<String, String> params) {

        if (!BaseUtils.isNetworkAvailable(this)) {
            //没有网络显示无网络
            mainMultiplestatusview.showNoNetwork();
            return;
        }

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().QueryAddressList(params))
                .compose(this.<BaseParse<AddressBean>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //显示加载中视图
                        mainMultiplestatusview.showLoading();
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new Observer<BaseParse<AddressBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParse<AddressBean> s) {
                        //处理得到的数据
                        attrRecyclerList(s.data.getAddressList());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理

                        mainMultiplestatusview.post(new Runnable() {
                            @Override
                            public void run() {
                                mainMultiplestatusview.showError();
                            }
                        });
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                    }
                });

    }


    //处理得到的list数据
    private void attrRecyclerList(List<Address> datas) {
        mData = datas;
        if (adapters != null) {
            adapters.clear();
            delegateAdapter.notifyDataSetChanged();
        }

        if (datas == null || datas.size() <= 0) {
            mainMultiplestatusview.showEmpty();
            return;
        }


        LinearLayoutHelper layoutHelper = new LinearLayoutHelper();
        layoutHelper.setDividerHeight(getResources().getDimensionPixelOffset(R.dimen.px30dp));
        if (adapters != null) {
            menuAdapter = new AddressAdapterRec(this, layoutHelper, datas);
            menuAdapter.setOnAddressMenuClick(menuClick);
            adapters.add(menuAdapter);
        }

        delegateAdapter.setAdapters(adapters);
        delegateAdapter.notifyDataSetChanged();


        mainMultiplestatusview.showContent();
    }


    //功能的回调
    AddressAdapterRec.OnAddressMenuClick menuClick = new AddressAdapterRec.OnAddressMenuClick() {
        @Override
        public void OnsetDefaultAddressClick(Address address, int oldposition,int position) {
            SetDefaultAddressRequest(address.getId(),oldposition,position);
        }

        @Override
        public void OnDeleteClick(Address address, int position) {
            RemoveAddressRequest(address.getId(), position);
        }

        @Override
        public void OnEditClick(Address address, int position) {

        }
    };

    /**
     * 调用设置默认收货地址--------------------------------------------------
     */
    private void SetDefaultAddressRequest(String addressid, final int oldposition, final int position) {
        //获取edit的值后请求

        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);   //用户id
        params.put("addressId",addressid);   //收货地址IDS


        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().SetDefaultAddressRequest(params))
                .compose(this.<BaseParse<String>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //显示加载中视图
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new Observer<BaseParse<String>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParse<String> s) {
                        //处理得到的数据
                        if (s.success) {
                            if (mData != null){
                                mData.get(oldposition).setDefault("0");
                                mData.get(position).setDefault("1");
                                if (menuAdapter != null){
                                    menuAdapter.notifyItemChanged(oldposition);
                                    menuAdapter.notifyItemChanged(position);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                    }
                });

    }


    /**
     * 调用删除收货地址--------------------------------------------------
     */
    private void RemoveAddressRequest(String addressid, final int position) {
        //获取edit的值后请求

        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);   //用户id
        params.put("addressId", addressid);   //收货地址IDS

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().RemoveAddressRequest(params))
                .compose(this.<BaseParse<String>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //显示加载中视图
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new Observer<BaseParse<String>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParse<String> s) {
                        //处理得到的数据
                        if (s.success) {
                            if (mData != null)
                                mData.remove(position);
                            if (menuAdapter != null)
                                menuAdapter.notifyItemRemoved(position);
                            if (position != mData.size())
                                menuAdapter.notifyItemRangeChanged(position, mData.size() - position);

                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                    }
                });
    }


    //初始化recyclerview
    private void initRecycler() {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        recAddresslist.setLayoutManager(layoutManager);


        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        recAddresslist.setRecycledViewPool(viewPool);

        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recAddresslist.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();
    }
}
